package cn.ncist.health_backend.service;

import cn.ncist.health_interface.service.UserService;
import cn.ncist.pojo.Permission;
import cn.ncist.pojo.Role;
import cn.ncist.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class SpringSecurityUserService implements UserDetailsService {
    //使用dubbo通过远程调用服务提供方获取数据库中的用户信息
    @DubboReference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //远程调用用户服务，根据用户名查询用户信息
        User user = userService.findUserByUsername(username);
        if (user == null){
            //用户名不存在
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        Set<Role> roleSet = user.getRoles();
        for (Role role : roleSet) {
            //授予用户角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissionSet = role.getPermissions();
            for (Permission permission : permissionSet) {
                //授予用户权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

//        UserDetails userDetails = new User(username,user.getPassword(),list)
//        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return securityUser;
    }
}
